<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-form-item label="站点名称">
              <el-select v-model="searchForm.siteId" placeholder="请选择站点" clearable style="width: 100%">
                <el-option v-for="item in siteOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <el-form-item label="设备名称">
              <el-input v-model="searchForm.keyword" placeholder="请输入设备名称" clearable style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <el-form-item label="设备状态">
              <el-select v-model="searchForm.status" placeholder="请选择设备状态" clearable style="width: 100%">
                <el-option label="全部" :value="''" />
                <el-option label="在线" value="online" />
                <el-option label="离线" value="offline" />
                <el-option label="告警" value="warn" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="时间范围">
              <el-date-picker v-model="searchForm.timeRange" type="datetimerange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <div class="form-actions">
              <el-button type="primary" @click="handleSearch" :loading="loading">
                <el-icon class="el-icon--left">
                  <Search />
                </el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch">
                <el-icon class="el-icon--left">
                  <Refresh />
                </el-icon>
                重置
              </el-button>
              <el-button type="success" @click="handleExport" :disabled="tableData.length === 0">
                <el-icon class="el-icon--left">
                  <Download />
                </el-icon>
                导出Excel
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card mt-2"> 
      <el-table :data="tableData" v-loading="loading" border  style="width: 100%">
        <el-table-column prop="siteName" label="站点名称" align="center" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.siteName || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="deviceName" label="设备名称" align="center" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.deviceName || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="deviceType" label="设备类型" align="center" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.deviceType || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="pointName" label="测点名称" align="center" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.pointName || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="pointCode" label="测点编码" align="center" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.pointCode || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="latestValue" label="瞬时流量(m³/h)" align="center" min-width="120">
          <template #default="{ row }">
            <span :class="getValueClass(row.latestValue)">
              {{ formatValue(row.latestValue) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="unit" label="单位" align="center" min-width="80">
          <template #default="{ row }">
            <span>{{ row.unit || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="deviceStatus" label="运行状态" align="center" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.deviceStatus)" size="small">
              {{ getStatusText(row.deviceStatus) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="rssi" label="信号强度" align="center" min-width="100">
          <template #default="{ row }">
            <span :class="getSignalClass(row.rssi)">
              {{ formatSignal(row.rssi) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="lastUploadTime" label="数据上传时间" align="center" min-width="160" sortable>
          <template #default="{ row }">
            <span>{{ formatTime(row.lastUploadTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="dataStatus" label="数据状态" align="center" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getDataStatusType(row.dataStatus)" size="small">
              {{ getDataStatusText(row.dataStatus) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="tableData.length > 0">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()

// API引入
import {
  getSiteList,
  getDeviceMonitorList
} from '@/api/dispatch/detection/equipment_monitoring'

// 搜索表单
const searchForm = reactive({
  siteId: '',
  keyword: '',
  status: '',
  timeRange: [
    dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss')
  ]
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 下拉选项
const siteOptions = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 初始化数据
onMounted(() => {
  initData()
})

// 初始化数据
const initData = async () => {
  try {
    await fetchSiteList()
    await fetchDeviceData()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 获取站点列表
const fetchSiteList = async () => {
  try {
    const res = await getSiteList()
    siteOptions.value = res.data || []
  } catch (error) {
    console.error('获取站点列表失败:', error)
    ElMessage.error('获取站点列表失败')
  }
}

// 获取设备监控数据
const fetchDeviceData = async () => {
  try {
    loading.value = true

    const params = {
      siteId: searchForm.siteId || '',
      status: searchForm.status,
      keyword: searchForm.keyword,
      beginTime: searchForm.timeRange?.[0] || '',
      endTime: searchForm.timeRange?.[1] || '',
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    const res = await getDeviceMonitorList(params)

    if (res.data) {
      tableData.value = res.data.records || []
      pagination.total = res.data.total || 0
    } else {
      tableData.value = []
      pagination.total = 0
    }

    if (tableData.value.length === 0) {
      ElMessage.warning('暂无数据')
    }
  } catch (error) {
    console.error('获取设备监控数据失败:', error)
    ElMessage.error('获取设备监控数据失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1
  fetchDeviceData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    siteId: '',
    keyword: '',
    status: '',
    timeRange: [
      dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().format('YYYY-MM-DD HH:mm:ss')
    ]
  })
  pagination.currentPage = 1
  pagination.pageSize = 10
  handleSearch()
}

// 导出Excel
const handleExport = async () => {
  try {
    if (tableData.value.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    const params = {
      siteId: searchForm.siteId || '',
      status: searchForm.status,
      keyword: searchForm.keyword,
      beginTime: searchForm.timeRange?.[0] || '',
      endTime: searchForm.timeRange?.[1] || '',
      pageNum: 1,
      pageSize: 10000
    }

    const fileName = `设备监控列表_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`

    // 使用proxy.download进行导出
    proxy.download('/dispatch/system/dispatchDeviceMonitor/export', params, fileName)
    ElMessage.success('导出任务已开始')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 刷新数据
const refreshData = () => {
  fetchDeviceData()
}

// 查看操作
const handleView = (row) => {
  console.log('查看设备:', row)
  ElMessage.info(`查看设备: ${row.deviceName}`)
}

// 详情操作
const handleDetail = (row) => {
  console.log('设备详情:', row)
  ElMessage.info(`查看设备详情: ${row.deviceName}`)
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchDeviceData()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchDeviceData()
}

// 工具函数
const formatValue = (value) => {
  if (value == null || value === '') return '-'
  if (typeof value === 'number') {
    return value.toFixed(2)
  }
  return value
}

const formatTime = (timeString) => {
  if (!timeString) return '-'
  try {
    return dayjs(timeString).format('YYYY-MM-DD HH:mm:ss')
  } catch {
    return timeString
  }
}

const formatSignal = (rssi) => {
  if (rssi == null) return '-'
  return `${rssi} dBm`
}

const getValueClass = (value) => {
  if (value == null) return ''
  if (typeof value === 'number') {
    if (value > 0) return 'value-normal'
    return 'value-zero'
  }
  return ''
}

const getStatusType = (status) => {
  switch (status) {
    case 'online': return 'success'
    case 'offline': return 'danger'
    case 'warn': return 'warning'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'online': return '在线'
    case 'offline': return '离线'
    case 'warn': return '告警'
    default: return status || '-'
  }
}

const getDataStatusType = (status) => {
  if (status === '正常') return 'success'
  if (status === '异常') return 'danger'
  return 'info'
}

const getDataStatusText = (status) => {
  return status || '-'
}

const getSignalClass = (rssi) => {
  if (rssi == null) return ''
  if (rssi >= -70) return 'signal-strong'
  if (rssi >= -85) return 'signal-medium'
  return 'signal-weak'
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}


.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px 0;
  background: #fafafa;
  border-radius: 4px;
}

/* 数值样式 */
.value-normal {
  color: #67c23a;
  font-weight: bold;
}

.value-zero {
  color: #909399;
}

/* 信号强度样式 */
.signal-strong {
  color: #67c23a;
  font-weight: bold;
}

.signal-medium {
  color: #e6a23c;
  font-weight: bold;
}

.signal-weak {
  color: #f56c6c;
  font-weight: bold;
}

</style>